using ASP;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using SysComm;
using ClassLibrary.BusinessLayer.Facade;
using SysOperationLayer.DBHandle;

public partial class ProjectInfo : Page, IRequiresSessionState
{
    private string projectCode = null;
    private string projectgroupid = null;
    private string projecttype = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        int iReturn = 0;
        string culture = ConvertToString(Session["Culture"]).ToLower();

        if (!Page.IsPostBack)
        {
            ibProjectInfo.ImageUrl = "~/Images/p_ProjInfo-" + culture + ".gif";
            ibViewDoc.ImageUrl = "~/Images/p_ViewDoc-" + culture + ".gif";
            ibProjectHeaderInfo.ImageUrl = "~/Images/p_AppProc-" + culture + ".gif";
            ibExpenditure.ImageUrl = "~/Images/p_Finance-" + culture + ".gif";
            lblError.Visible = false;
            btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");

            CountriesDB objDB = new CountriesDB();
            DataTable dt = objDB.GetInfo();

            ddlPriorityCountry.DataSource = dt;
            ddlPriorityCountry.DataTextField = "EnglishName";
            ddlPriorityCountry.DataValueField = "Country";
            ddlPriorityCountry.DataBind();

            ddlCountry.DataSource = dt;
            ddlCountry.DataTextField = "EnglishName";
            ddlCountry.DataValueField = "Country";
            ddlCountry.DataBind();

            ddlStatus.DataSource = new CodeDB(objDB.GetDB()).GetInfo("PS");
            ddlStatus.DataTextField = "Code";
            ddlStatus.DataValueField = "Code";
            ddlStatus.DataBind();

            ddlType.DataSource = new CodeDB(objDB.GetDB()).GetInfo("PT");
            ddlType.DataTextField = "Code";
            ddlType.DataValueField = "Code";
            ddlType.DataBind();

            gvChooseProjectClass.DataSource = new ProjectClassDB(objDB.GetDB()).GetInfo();
            gvChooseProjectClass.DataBind();

            if ((base.Request.QueryString["np"].ToString() == "1") && (base.Request.QueryString["di"].ToString() == "0"))
            {
                txtProjectGroupID.Text = base.Request.QueryString["pgi"].ToString();
                iReturn = Add(sender, e);
                txtProjectGroupID.Enabled = true;
                txtProjectGroupID.Focus();
                PrjInfoPanel.Visible = true;
                ProjectListPanel.Visible = false;
                ibExpenditure.Visible = true;
                ibProjectHeaderInfo.Visible = true;
                ibProjectInfo.Visible = true;
                ibViewDoc.Visible = true;
                ibGeneral.ImageUrl = "~/Images/a_General_blue-" + culture + ".gif";
                ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
                ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
                ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
                PanelGeneral.Visible = true;
                btnModify.Visible = true;
                btnSave.Visible = true;
                btnDelete.Visible = true;
                btnCancel.Visible = true;
                projecttype = txtType.Text;
                setButtons("new");

                if (iReturn != 0)
                {
                    btnSave.Visible = false;
                }
            }
            else
            {
                try
                {
                    projectgroupid = base.Request.QueryString["pgi"].ToString();
                    projectCode = base.Request.QueryString["pc"].ToString();
                    projecttype = base.Request.QueryString["type"].ToString();

                    if (string.IsNullOrEmpty(projectgroupid))
                    {
                        try
                        {
                            projectgroupid = base.Request.QueryString["projectGroupId"].ToString();
                            projectCode = base.Request.QueryString["projectCode"].ToString();
                            projecttype = base.Request.QueryString["projectType"].ToString();
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                catch (NullReferenceException)
                {
                }

                if (string.IsNullOrEmpty(projectCode))
                {
                    ibGeneral.Visible = false;
                    ibAgent.Visible = false;
                    ibClient.Visible = false;
                    ibOthers.Visible = false;
                    btnModify.Visible = false;
                    btnSave.Visible = false;
                    btnDelete.Visible = false;
                    btnCancel.Visible = false;
                    PrjInfoPanel.Visible = false;
                    ProjectListPanel.Visible = true;
                    ibExpenditure.Visible = false;
                    ibProjectHeaderInfo.Visible = false;
                    ibProjectInfo.Visible = false;
                    ibViewDoc.Visible = false;
                    GridView1.DataBind();
                    lblNoRecords.Visible = GridView1.Rows.Count == 0;
                }
                else
                {
                    ViewState["isRestore"] = false;

                    if (Session["SuperUser"] != null && base.Request.QueryString["isd"] != null)
                    {
                        if (Convert.ToBoolean(Session["SuperUser"]) && base.Request.QueryString["isd"].ToString() == "1")
                        {
                           ViewState["isRestore"] = true;
                        }
                    }

                    LoadProjectInfo(base.Request.QueryString["pgi"].ToString(), projectCode, base.Request.QueryString["type"].ToString());
                    ibViewDoc.Visible = SysUtil.IsAdministratorUsertype() || SysUtil.IsManagementSupervisor() || SysUtil.IsEngineer() ||  new ProjectDB(objDB.GetDB()).IsResponsiblePersonOwner(txtProjectCode.Text.Trim(), Session[SysUtil.m_str_session_loginname].ToString());
                    ibProjectHeaderInfo.Visible = ibViewDoc.Visible;
                    ibExpenditure.Visible = ibViewDoc.Visible && !SysUtil.IsEngineer();
                }
            }

            objDB.CloseDB();
            SetGrantDate();
        }

        lblError.Text = "";
        lbResponsiblePerson.Enabled = base.Request.QueryString["np"].ToString() == "0";
    }

    protected int Add(object sender, EventArgs e)
    {
        //Auth canAdd = new Auth(Session["UserId"].ToString(), string.Empty, "ProjectInfo");
        Project pj = new Project();
        List<string> values = new List<string>();
        int Count = pj.GetLicenseCount();

        /*if ((Count <= pj.GetUserProjectCount(Session[SysUtil.m_str_session_loginname].ToString())) & (Count != 0x1a))
        {
            lblError.Visible = true;
            values.Add(Count.ToString());
            lblError.Text = IPDataFormat.GenerateMessage(Messages.mProjectCount.ToString(), values);
            return -1;
        }*/

        /*if (!canAdd.CanAdd())
        {
            lblError.Visible = true;
            lblError.Text = Messages.mNoAdd.ToString();
            return -1;
        }*/

        clearText();
        setButtons("new");
        setTextReadOnly(false);
        txtProjectCode.Focus();
        Session["IsNewRecord"] = "Yes";
        GetProjectDefault();
        EnabledDisabledPriority("New");
        if (chkFirstFiling.Checked)
        {
            txtFilingDate.CssClass = "required";
            RequiredFieldValidator5.Enabled = true;
        }
        else
        {
            txtFilingDate.CssClass = "";
            RequiredFieldValidator5.Enabled = false;
        }
        return 0;
    }

    protected void OnClick(object sender, EventArgs e)
    {
        if (sender == btnNew)
        {
            Add(sender, e);
        }
        else if (sender == btnModify)
        {
            setButtons("modify");
            setTextReadOnly(false);
            txtProjectCode.ReadOnly = true;
            txtProjectCode.Enabled = false;
            btnPGI.Enabled = false;
            ddlCountry.Focus();
            txtType.Enabled = false;
            Session["IsNewRecord"] = "No";
            chkForUpdate.Checked = true;
            chkForOperation.Checked = true;
            GetProjectDefault();
            EnabledDisabledPriority("Edit");
            PCTProcess(true);
            Page.SetFocus("txtTitleSubject");
        }
        else if (sender == btnSave)
        {
            string bIsNewRec = Session["IsNewRecord"].ToString();

            try
            {
                if ((txtPatentNumber.Text.Length != 0) && (IPDataFormat.FormatDateTime(txtGrantDate.Text) == ""))
                {
                    throw new Exception(Messages.mGrantDate_Required.ToString());
                }

                if ((txtPatentNumber.Text.Length != 0)
                    && (IPDataFormat.GetValidDateTime(IPDataFormat.ConvertDateFormat(txtFilingDate.Text.ToString(), 1))
                        >= IPDataFormat.GetValidDateTime(IPDataFormat.ConvertDateFormat(txtGrantDate.Text.ToString(), 1))))
                {

                    throw new Exception(Messages.mGrantDate_GE_FilingDate.ToString());
                }

                if (txtProjectCode.Text.Contains("&"))
                {
                    throw new Exception(Messages.mInvalidProjectCode.ToString());
                }

                if ((txtPatentNumber.Text.Length != 0) && (txtGrantDate.Text.Length == 0))
                {
                    throw new Exception(Messages.mGrantDateCannotBeNull.ToString());
                }

                if (bIsNewRec == "Yes")
                {
                    ODSProjects.InsertMethod = "Insert";
                    ODSProjects.InsertParameters["ProjectCode"].DefaultValue = txtProjectCode.Text.ToString();
                    ODSProjects.InsertParameters["Type"].DefaultValue = txtType.Text;
                    ODSProjects.InsertParameters["Status"].DefaultValue = ddlStatus.SelectedValue.ToString();
                    ODSProjects.InsertParameters["Country"].DefaultValue = ddlCountry.SelectedValue.ToString();
                    ODSProjects.InsertParameters["Agent"].DefaultValue = txtAgent.Text.ToString();
                    ODSProjects.InsertParameters["Title"].DefaultValue = txtTitleSubject.Text.ToString();
                    ODSProjects.InsertParameters["Applicant"].DefaultValue = txtApplicant.Text.ToString();
                    ODSProjects.InsertParameters["Inventor"].DefaultValue = txtInventor.Text.ToString();
                    ODSProjects.InsertParameters["ApplicationNo"].DefaultValue = txtApplicationNo.Text.ToString();
                    ODSProjects.InsertParameters["PatentNumber"].DefaultValue = txtPatentNumber.Text.ToString();
                    ODSProjects.InsertParameters["PriorityDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtPriorityDate.Text.ToString(), 1);
                    ODSProjects.InsertParameters["PriorityCountry"].DefaultValue = ddlPriorityCountry.SelectedValue.ToString();
                    ODSProjects.InsertParameters["ClientName"].DefaultValue = txtClient.Text.ToString();
                    ODSProjects.InsertParameters["FilingDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtFilingDate.Text.ToString(), 1);
                    ODSProjects.InsertParameters["GrantDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtGrantDate.Text.ToString(), 1);
                    ODSProjects.InsertParameters["FirstFilingYN"].DefaultValue = chkFirstFiling.Checked ? "true" : "false";
                    ODSProjects.InsertParameters["ProjectGroupID"].DefaultValue = txtProjectGroupID.Text.ToString();
                    ODSProjects.InsertParameters["PublicationNumber"].DefaultValue = txtPublicationNumber.Text.ToString();
                    ODSProjects.InsertParameters["Remark"].DefaultValue = txtRemarks.Text.ToString();
                    ODSProjects.InsertParameters["CreateBy"].DefaultValue = Session[SysUtil.m_str_session_loginname].ToString();
                    ODSProjects.InsertParameters["UpdateBy"].DefaultValue = Session[SysUtil.m_str_session_loginname].ToString();
                    ODSProjects.InsertParameters["OwnerGroupID"].DefaultValue = Session["OwnerGroupId"].ToString();
                    ODSProjects.InsertParameters["ProjectClass"].DefaultValue = txtProjectClass.Text.ToString();
                    ODSProjects.InsertParameters["Priority"].DefaultValue = chkPriority.Checked ? "true" : "false";
                    ODSProjects.InsertParameters["PCTYN"].DefaultValue = chkPCT.Checked ? "true" : "false";
                    ODSProjects.InsertParameters["AgentContactPerson3"].DefaultValue = txtAgentContactPerson3.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactFax3"].DefaultValue = txtAgentContactFax3.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactPhone3"].DefaultValue = txtAgentContactPhone3.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactEmailAddress3"].DefaultValue = txtAgentContactEmail3.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactPerson4"].DefaultValue = txtAgentContactPerson4.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactFax4"].DefaultValue = txtAgentContactFax4.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactPhone4"].DefaultValue = txtAgentContactPhone4.Text.ToString();
                    ODSProjects.InsertParameters["AgentContactEmailAddress4"].DefaultValue = txtAgentContactEmail4.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactPerson3"].DefaultValue = txtClientContactPerson3.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactFax3"].DefaultValue = txtClientContactFax3.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactPhone3"].DefaultValue = txtClientContactPhone3.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactEmailAddress3"].DefaultValue = txtClientContactEmail3.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactPerson4"].DefaultValue = txtClientContactPerson4.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactFax4"].DefaultValue = txtClientContactFax4.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactPhone4"].DefaultValue = txtClientContactPhone4.Text.ToString();
                    ODSProjects.InsertParameters["ClientContactEmailAddress4"].DefaultValue = txtClientContactEmail4.Text.ToString();
                    ODSProjects.InsertParameters["CreateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                    ODSProjects.Insert();
                    new ProjectSupervisor(txtProjectCode.Text.ToString(), Session[SysUtil.m_str_session_loginname].ToString(), Session["OwnerGroupId"].ToString()).CreateResponsiblePerson();
                }
                else
                {
                    ODSProjects.UpdateMethod = "Update";
                    ODSProjects.UpdateParameters["Type"].DefaultValue = txtType.Text;
                    ODSProjects.UpdateParameters["Status"].DefaultValue = ddlStatus.SelectedValue.ToString();
                    ODSProjects.UpdateParameters["Country"].DefaultValue = ddlCountry.SelectedValue.ToString();
                    ODSProjects.UpdateParameters["Agent"].DefaultValue = txtAgent.Text.ToString();
                    ODSProjects.UpdateParameters["Title"].DefaultValue = txtTitleSubject.Text.ToString();
                    ODSProjects.UpdateParameters["Applicant"].DefaultValue = txtApplicant.Text.ToString();
                    ODSProjects.UpdateParameters["Inventor"].DefaultValue = txtInventor.Text.ToString();
                    ODSProjects.UpdateParameters["ApplicationNo"].DefaultValue = txtApplicationNo.Text.ToString();
                    ODSProjects.UpdateParameters["PatentNumber"].DefaultValue = txtPatentNumber.Text.ToString();
                    ODSProjects.UpdateParameters["PriorityDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtPriorityDate.Text.ToString(), 1);
                    ODSProjects.UpdateParameters["PriorityCountry"].DefaultValue = ddlPriorityCountry.SelectedValue.ToString();
                    ODSProjects.UpdateParameters["ClientName"].DefaultValue = txtClient.Text.ToString();
                    ODSProjects.UpdateParameters["FilingDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtFilingDate.Text.ToString(), 1);
                    ODSProjects.UpdateParameters["GrantDate"].DefaultValue = IPDataFormat.ConvertDateFormat(txtGrantDate.Text.ToString(), 1);
                    ODSProjects.UpdateParameters["FirstFilingYN"].DefaultValue = chkFirstFiling.Checked ? "true" : "false";
                    ODSProjects.UpdateParameters["ProjectGroupID"].DefaultValue = txtProjectGroupID.Text.ToString();
                    ODSProjects.UpdateParameters["PublicationNumber"].DefaultValue = txtPublicationNumber.Text.ToString();
                    ODSProjects.UpdateParameters["Remark"].DefaultValue = txtRemarks.Text.ToString();
                    ODSProjects.UpdateParameters["UpdateBy"].DefaultValue = Session[SysUtil.m_str_session_loginname].ToString();
                    ODSProjects.UpdateParameters["OwnerGroupID"].DefaultValue = Session["OwnerGroupId"].ToString();
                    ODSProjects.UpdateParameters["Original_ProjectCode"].DefaultValue = txtProjectCode.Text.ToString();
                    ODSProjects.UpdateParameters["ProjectClass"].DefaultValue = txtProjectClass.Text.ToString();
                    ODSProjects.UpdateParameters["Priority"].DefaultValue = chkPriority.Checked ? "true" : "false";
                    ODSProjects.UpdateParameters["PCTYN"].DefaultValue = chkPCT.Checked ? "true" : "false";
                    ODSProjects.UpdateParameters["AgentContactPerson3"].DefaultValue = txtAgentContactPerson3.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactFax3"].DefaultValue = txtAgentContactFax3.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactPhone3"].DefaultValue = txtAgentContactPhone3.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactEmailAddress3"].DefaultValue = txtAgentContactEmail3.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactPerson4"].DefaultValue = txtAgentContactPerson4.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactFax4"].DefaultValue = txtAgentContactFax4.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactPhone4"].DefaultValue = txtAgentContactPhone4.Text.ToString();
                    ODSProjects.UpdateParameters["AgentContactEmailAddress4"].DefaultValue = txtAgentContactEmail4.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactPerson3"].DefaultValue = txtClientContactPerson3.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactFax3"].DefaultValue = txtClientContactFax3.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactPhone3"].DefaultValue = txtClientContactPhone3.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactEmailAddress3"].DefaultValue = txtClientContactEmail3.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactPerson4"].DefaultValue = txtClientContactPerson4.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactFax4"].DefaultValue = txtClientContactFax4.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactPhone4"].DefaultValue = txtClientContactPhone4.Text.ToString();
                    ODSProjects.UpdateParameters["ClientContactEmailAddress4"].DefaultValue = txtClientContactEmail4.Text.ToString();
                    ODSProjects.UpdateParameters["UpdateIP"].DefaultValue = HttpContext.Current.Request.UserHostAddress;
                    //ODSProjects.UpdateParameters["UpdateDate"].DefaultValue = DateTime.Now.ToString();
                    ODSProjects.Update();
                }

                ODSProjects.Select();
                Session["fromReminder"] = "1";
                string RefreshParent_javaScript = "<script type='text/javascript' language='javascript'> \n";
                string strname = RefreshParent_javaScript;
                RefreshParent_javaScript = (strname + "window.parent.location = 'OptProjectDefault.aspx?projectGroupId=" + txtProjectGroupID.Text.ToString() + "&projectCode=" + txtProjectCode.Text.ToString() + "&projectType=" + txtType.Text + "&np=0'") + "</script>";
                base.ClientScript.RegisterStartupScript(Page.GetType(), "RefreshParent", RefreshParent_javaScript);

                LogDB objDB = new LogDB();

                if (bIsNewRec == "Yes")
                {
                    objDB.writeSucLog(SysUtil.m_functiong_project, "Create New Project succeed!");
                }
                else
                {
                    objDB.writeSucLog(SysUtil.m_functiong_project, "Update Project succeed!");
                }

                objDB.CloseDB();
            }
            catch (Exception ex)
            {
                List<string> lstValues = new List<string>();
                lstValues.Add(Strings.ProjectInformation.ToString());
                //lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
                lblError.Text = ex.Message.ToString();
                lblError.Visible = true;
                chkForOperation.Checked = true;

                LogDB objDB = new LogDB();

                if (bIsNewRec == "Yes")
                {
                    objDB.writeFaileLog(SysUtil.m_functiong_project, "Fail To Create New Project!");
                }
                else
                {
                    objDB.writeFaileLog(SysUtil.m_functiong_project, "Fail To Update Project!");
                }

                objDB.CloseDB();
            }

            chkForUpdate.Checked = false;
        }
        else if (sender == btnDelete)
        {
            ProjectDB objDB = new ProjectDB();

            if (objDB.Delete(txtProjectCode.Text, Session[SysUtil.m_str_session_loginname].ToString(), HttpContext.Current.Request.UserHostAddress) == 0)
            {
                new LogDB(objDB.GetDB()).writeSucLog(SysUtil.m_functiong_project, "Delete Project Success! Project Code: " + txtProjectCode.Text);
                GridView1.DataBind();
                OnClick(btnCancel, null);
                lblNoRecords.Visible = GridView1.Rows.Count == 0;
            }
            else
            {
                new LogDB(objDB.GetDB()).writeSucLog(SysUtil.m_functiong_project, "Delete Project Failure! Project Code: " + txtProjectCode.Text);
            }
            
            objDB.CloseDB();
        }
        else if (sender == btnRestore)
        {
            ProjectDB objDB = new ProjectDB();

            if (objDB.Restore(txtProjectCode.Text, Session[SysUtil.m_str_session_loginname].ToString(), HttpContext.Current.Request.UserHostAddress) == 0)
            {
                new LogDB(objDB.GetDB()).writeSucLog(SysUtil.m_functiong_project, "Restore Project Success! Project Code: " + txtProjectCode.Text);
                GridView1.DataBind();
                OnClick(btnCancel, null);
                lblNoRecords.Visible = GridView1.Rows.Count == 0;
            }
            else
            {
                new LogDB(objDB.GetDB()).writeSucLog(SysUtil.m_functiong_project, "Restore Project Failure! Project Code: " + txtProjectCode.Text);
            }

            objDB.CloseDB();
        }
        else if (sender == btnCancel)
        {
            setButtons(string.Empty);
            setTextReadOnly(true);
            PanelGeneral.Visible = false;
            PanelAgent.Visible = false;
            PanelClient.Visible = false;
            PanelOther.Visible = false;
            PrjInfoPanel.Visible = false;
            ProjectListPanel.Visible = true;
            ibGeneral.Visible = false;
            ibAgent.Visible = false;
            ibClient.Visible = false;
            ibOthers.Visible = false;
            btnModify.Visible = false;
            btnSave.Visible = false;
            btnDelete.Visible = false;
            btnCancel.Visible = false;
            ibExpenditure.Visible = false;
            ibProjectHeaderInfo.Visible = false;
            ibProjectInfo.Visible = false;
            ibViewDoc.Visible = false;
            lblNoRecords.Visible = false;

            try
            {
                if (base.Request.QueryString["np"].ToString() == "1")
                {
                }
            }
            catch (Exception)
            {
            }
        }
        else if (sender == btnAgent)
        {
            if ((Session["SelectedAgent"] != null) && (Session["SelectedAgent"].ToString() != ""))
            {
                string Result = Session["SelectedAgent"].ToString();
                AgentsFacade facade = new AgentsFacade();
                SqlParameter[] sqlparam = new SqlParameter[4];
                sqlparam[0] = new SqlParameter();
                sqlparam[0].ParameterName = "@Agent";
                sqlparam[0].Value = Result;
                sqlparam[1] = new SqlParameter();
                sqlparam[1].ParameterName = "@Name";
                sqlparam[1].Value = "";
                sqlparam[2] = new SqlParameter();
                sqlparam[2].ParameterName = "@ChineseName";
                sqlparam[2].Value = "";
                sqlparam[3] = new SqlParameter();
                sqlparam[3].ParameterName = "@ContactPerson";
                sqlparam[3].Value = "";
                DbParameter[] param = sqlparam;
                DataTable dt = facade.GetsAgents("_IPMS_AgentSelect_SP", param);
                txtAgent.Text = dt.Rows[0]["Agent"].ToString();
                txtAgentName.Text = dt.Rows[0]["Name"].ToString();
                txtAgentChineseName.Text = dt.Rows[0]["ChineseName"].ToString();
                txtAgentContactPerson.Text = dt.Rows[0]["ContactPerson"].ToString();
                txtAgentAddress.Text = dt.Rows[0]["Address"].ToString();
                txtAgentWebSite.Text = dt.Rows[0]["WebSite"].ToString();
                txtAgentFaxNo.Text = dt.Rows[0]["Fax"].ToString();
                txtAgentPhoneNo.Text = dt.Rows[0]["Phone"].ToString();
                txtAgentPhoneNo2.Text = dt.Rows[0]["Phone2"].ToString();
                txtAgentContactPerson2.Text = dt.Rows[0]["ContactPerson2"].ToString();
                txtAgentFaxNo2.Text = dt.Rows[0]["Fax2"].ToString();
                txtAgentEmailAddress.Text = dt.Rows[0]["EmailAddress"].ToString();
                txtAgentEmailAddress2.Text = dt.Rows[0]["EmailAddress2"].ToString();
                Session.Remove("SelectedAgent");
            }
        }
        else if (sender == btnClient)
        {
            if ((Session["SelectedClient"] != null) && (Session["SelectedClient"].ToString() != ""))
            {
                string Result = Session["SelectedClient"].ToString();
                AgentsFacade facade = new AgentsFacade();
                SqlParameter[] sqlparam = new SqlParameter[4];
                sqlparam[0] = new SqlParameter();
                sqlparam[0].ParameterName = "@Client";
                sqlparam[0].Value = Result;
                sqlparam[1] = new SqlParameter();
                sqlparam[1].ParameterName = "@Name";
                sqlparam[1].Value = "";
                sqlparam[2] = new SqlParameter();
                sqlparam[2].ParameterName = "@ChineseName";
                sqlparam[2].Value = "";
                sqlparam[3] = new SqlParameter();
                sqlparam[3].ParameterName = "@ContactPerson";
                sqlparam[3].Value = "";

                DbParameter[] param = sqlparam;
                DataTable dt = facade.GetsAgents("_IPMS_ClientSelect_SP", param);
                txtClient.Text = dt.Rows[0]["Client"].ToString();
                txtClientName.Text = dt.Rows[0]["Name"].ToString();
                txtClientChineseName.Text = dt.Rows[0]["ChineseName"].ToString();
                txtClientContactPerson.Text = dt.Rows[0]["ContactPerson"].ToString();
                txtClientAddress.Text = dt.Rows[0]["Address"].ToString();
                txtClientWebSite.Text = dt.Rows[0]["WebSite"].ToString();
                txtClientFax.Text = dt.Rows[0]["Fax"].ToString();
                txtClientPhone.Text = dt.Rows[0]["Phone"].ToString();
                txtClientPhone2.Text = dt.Rows[0]["Phone2"].ToString();
                txtClientContactPerson2.Text = dt.Rows[0]["ContactPerson2"].ToString();
                txtClientFax2.Text = dt.Rows[0]["Fax2"].ToString();
                txtClientEmailAddress.Text = dt.Rows[0]["EmailAddress"].ToString();
                txtClientEmailAddress2.Text = dt.Rows[0]["EmailAddress2"].ToString();
                Session.Remove("SelectedClient");
            }
        }
        else if (sender == btnPGI)
        {
            if ((Session["SelectedProjectGroup"] != null) && (Session["SelectedProjectGroup"].ToString() != ""))
            {
                txtProjectGroupID.Text = Session["SelectedProjectGroup"].ToString();
                GetProjectDefault();
                EnabledDisabledPriority("New");
            }
        }
        else if (sender == lbResponsiblePerson)
        {
            ProjectDB objDB = new ProjectDB();
            grdProjectResponsiblePerson.DataSource = objDB.GetResponsiblePerson(txtProjectCode.Text.Trim());
            grdProjectResponsiblePerson.DataBind();
            objDB.CloseDB();
        }
    }

    protected void SetAgentBlank()
    {
        txtAgent.Text = string.Empty;
        txtAgentName.Text = string.Empty;
        txtAgentChineseName.Text = string.Empty;
        txtAgentContactPerson.Text = string.Empty;
        txtAgentAddress.Text = string.Empty;
        txtAgentWebSite.Text = string.Empty;
        txtAgentFaxNo.Text = string.Empty;
        txtAgentPhoneNo.Text = string.Empty;
        txtAgentPhoneNo2.Text = string.Empty;
        txtAgentContactPerson2.Text = string.Empty;
        txtAgentFaxNo2.Text = string.Empty;
        txtAgentEmailAddress.Text = string.Empty;
        txtAgentEmailAddress2.Text = string.Empty;
    }

    protected void SetClientBlank()
    {
        txtClient.Text = string.Empty;
        txtClientName.Text = string.Empty;
        txtClientChineseName.Text = string.Empty;
        txtClientContactPerson.Text = string.Empty;
        txtClientAddress.Text = string.Empty;
        txtClientWebSite.Text = string.Empty;
        txtClientFax.Text = string.Empty;
        txtClientPhone.Text = string.Empty;
        txtClientPhone2.Text = string.Empty;
        txtClientContactPerson2.Text = string.Empty;
        txtClientFax2.Text = string.Empty;
        txtClientEmailAddress.Text = string.Empty;
        txtClientEmailAddress2.Text = string.Empty;
    }

    protected void OnCheckedChanged(object sender, EventArgs e)
    {
        if (sender == chkFirstFiling)
        {
            if (chkFirstFiling.Checked)
            {
                txtFilingDate.CssClass = "required";
                RequiredFieldValidator5.Enabled = true;
                txtFilingDate.Enabled = true;
                if (txtFilingDate.Text == "")
                {
                    txtFilingDate.Text = IPDataFormat.ConvertDateFormat(DateTime.Now.ToShortDateString(), 2);
                }
                txtPriorityDate.Text = "";
            }
            else
            {
                txtFilingDate.CssClass = "";
                RequiredFieldValidator5.Enabled = false;
                txtFilingDate.Enabled = true;
            }
        }
        else if (sender == chkPCT)
        {
            PCTProcess(false);
            if (!chkPCT.Checked)
            {
                txtPriorityDate.Text = "";
            }
            if (chkPCT.Checked)
            {
                txtPriorityDate.Text = txtFilingDate.Text;
            }
        }
        else if (sender == chkPriority)
        {
            if (chkPriority.Checked)
            {
                try
                {
                    ProjectGroupClass runMethod = new ProjectGroupClass();
                    runMethod.GetProjectGroupInfo(txtProjectGroupID.Text);

                    if (runMethod.FirstFilingDate != null && runMethod.FirstFilingDate.ToString("yyyy").CompareTo("1900") >= 0)
                    {
                        txtPriorityDate.Text = runMethod.FirstFilingDate.ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        txtPriorityDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    }

                    txtPriorityDate.Enabled = true;
                    ddlPriorityCountry.ClearSelection();
                    ddlPriorityCountry.Items.FindByValue(Session["PCTCountry"].ToString()).Selected = true;
                    ddlPriorityCountry.Enabled = true;
                }
                catch
                {
                    ddlPriorityCountry.SelectedIndex = -1;
                    ddlPriorityCountry.Items.FindByValue("").Selected = true;
                }
            }
            else
            {
                ddlPriorityCountry.SelectedIndex = -1;
                ddlPriorityCountry.Items.FindByValue("").Selected = true;
                txtPriorityDate.Text = "";
            }
        }
    }

    private void clearText()
    {
        txtProjectCode.Text = string.Empty;
        txtType.Text = "";
        ddlStatus.SelectedIndex = 0;
        ddlCountry.SelectedIndex = 0;
        txtAgent.Text = string.Empty;
        chkPCT.Checked = false;
        txtAgentName.Text = string.Empty;
        txtAgentChineseName.Text = string.Empty;
        txtAgentContactPerson.Text = string.Empty;
        txtAgentAddress.Text = string.Empty;
        txtAgentWebSite.Text = string.Empty;
        txtAgentFaxNo.Text = string.Empty;
        txtAgentPhoneNo.Text = string.Empty;
        txtAgentPhoneNo2.Text = string.Empty;
        txtAgentContactPerson2.Text = string.Empty;
        txtAgentFaxNo2.Text = string.Empty;
        txtAgentEmailAddress.Text = string.Empty;
        txtAgentEmailAddress2.Text = string.Empty;
        txtAgentContactPerson3.Text = string.Empty;
        txtAgentContactFax3.Text = string.Empty;
        txtAgentContactPhone3.Text = string.Empty;
        txtAgentContactEmail3.Text = string.Empty;
        txtAgentContactPerson4.Text = string.Empty;
        txtAgentContactFax4.Text = string.Empty;
        txtAgentContactPhone4.Text = string.Empty;
        txtAgentContactEmail4.Text = string.Empty;
        txtTitleSubject.Text = string.Empty;
        txtApplicant.Text = string.Empty;
        txtInventor.Text = string.Empty;
        txtApplicationNo.Text = string.Empty;
        txtPatentNumber.Text = string.Empty;
        txtPriorityDate.Text = string.Empty;
        ddlPriorityCountry.SelectedIndex = 0;
        txtClient.Text = string.Empty;
        txtFilingDate.Text = string.Empty;
        txtGrantDate.Text = string.Empty;
        txtFilingDate.Text = string.Empty;
        txtPublicationNumber.Text = string.Empty;
        txtRemarks.Text = string.Empty;
        txtProjectClass.Text = string.Empty;
        chkFirstFiling.Checked = false;
        chkPriority.Checked = false;
        chkForUpdate.Checked = false;
        chkForOperation.Checked = false;
    }

    protected void OnPreRender(object sender, EventArgs e)
    {
        try
        {
            if (sender == ddlCountry)
            {
                if (ddlCountry.Text == "")
                {
                    Project runMethod = new Project();
                    runMethod.GetProjectInfo(projectgroupid, projectCode, projecttype);
                    ddlCountry.ClearSelection();
                    ddlCountry.Items.FindByValue(runMethod.Country).Selected = true;
                }
            }
            else if (sender == ddlPriorityCountry)
            {
                if (ddlPriorityCountry.Text == "")
                {
                    Project runMethod = new Project();
                    runMethod.GetProjectInfo(projectgroupid, projectCode, projecttype);
                    ddlPriorityCountry.SelectedIndex = -1;
                    ddlPriorityCountry.Items.FindByValue(runMethod.PriorityCountry).Selected = true;
                }
            }
            else if (sender == ddlStatus)
            {
                if (!Page.IsPostBack | (ddlStatus.Text == ""))
                {
                    if (base.Request.QueryString["np"].ToString() == "0")
                    {
                        Project runMethod = new Project();
                        runMethod.GetProjectInfo(projectgroupid, projectCode, projecttype);
                        ddlStatus.SelectedIndex = -1;
                        ddlStatus.Items.FindByValue(runMethod.Status).Selected = true;
                    }
                    else
                    {
                        ddlStatus.SelectedIndex = -1;
                        ddlStatus.Items.FindByText("Pending").Selected = true;
                    }
                }
            }
        }
        catch (Exception)
        {
        }
    }

    protected void OnSelectedIndexChanged(object sender, EventArgs e)
    {
        if (sender == ddlCountry)
        {
            SetPCT(ddlCountry.SelectedValue);

            if (chkPCT.Checked & (txtType.Text == "Patent"))
            {
                txtPriorityDate.Text = txtFilingDate.Text;
                txtPriorityDate.Enabled = false;
            }

            if (!chkPCT.Checked & (txtType.Text == "Patent"))
            {
                txtPriorityDate.Text = "";
                txtPriorityDate.Enabled = true;
            }

            if (chkPriority.Checked)
            {
                txtPriorityDate.Enabled = false;
            }
        }
        else if (sender == GridView1)
        {
            projectCode = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();
            string isDelete = GridView1.DataKeys[GridView1.SelectedIndex].Values["IsDelete"].ToString();

            ViewState["isRestore"] = false;

            if (Session["SuperUser"] != null)
            {
                if (Convert.ToBoolean(Session["SuperUser"]) && Convert.ToBoolean(isDelete))
                {
                    ViewState["isRestore"] = true;
                }
            }

            Session["projectCode"] = projectCode.ToString();
            setButtons(string.Empty);
            LoadProjectInfo(base.Request.QueryString["pgi"].ToString(), projectCode, GridView1.DataKeys[GridView1.SelectedIndex]["Type"].ToString());
            SetGrantDate();
            lbResponsiblePerson.Enabled = base.Request.QueryString["np"].ToString() == "0";
            string culture = ConvertToString(Session["Culture"]).ToLower();
            ibGeneral.ImageUrl = "~/Images/a_General_blue-" + culture + ".gif";
            ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
            ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
            ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
            ibGeneral.Visible = true;
            ibAgent.Visible = true;
            ibClient.Visible = true;
            ibOthers.Visible = true;
        }
        else if (sender == gvChooseProjectClass)
        {
            txtProjectClass.Text = gvChooseProjectClass.DataKeys[gvChooseProjectClass.SelectedIndex].Values["ProjectClass"].ToString();
        }
    }

    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        Sort(e, GridView1);
    }

    private void EnabledDisabledPriority(string Mode)
    {
        chkFirstFiling.Enabled = false;
        if ((Session["FirstFilingEnabled"].ToString() == "1") | Convert.ToBoolean(Session["SuperUser"].ToString()))
        {
            chkFirstFiling.Enabled = true;
            if (chkFirstFiling.Checked)
            {
                txtFilingDate.Enabled = false;
            }
            else
            {
                txtFilingDate.Enabled = true;
            }
        }
        else
        {
            chkFirstFiling.Enabled = false;
            txtFilingDate.Enabled = false;
        }
        if (!(chkFirstFiling.Checked || !(Session["FirstFilingEnabled"].ToString() == "0")))
        {
            chkFirstFiling.Enabled = false;
            txtFilingDate.Enabled = true;
        }
        if ((Session["FirstFilingEnabled"].ToString() == "1") | ((Session["FirstFilingEnabled"].ToString() == "0") && (txtProjectCode.Text.ToString() == Session["TargetProjectCode"].ToString())))
        {
            txtPriorityDate.Enabled = false;
            ddlPriorityCountry.Enabled = false;
        }
        if (Mode == "New")
        {
            txtProjectClass.Text = Session["ProjectClass"].ToString();
        }
        if (txtProjectGroupID.Text == "")
        {
            chkFirstFiling.Enabled = false;
            txtFilingDate.Enabled = false;
        }
    }

    protected void EnableDisableByProjectType()
    {
        string strname0 = projecttype;

        if (strname0 != null)
        {
            if (!(strname0 == "Design"))
            {
                if (strname0 == "Trademark")
                {
                    lblInventor.Text = Strings.Inventor.ToString();
                    lblPatentNumber.Text = Strings.RegistrationNumber.ToString();
                    chkPCT.Visible = false;
                    Panel1.Visible = true;
                    chkFirstFiling.Visible = true;
                }
                else if (strname0 == "Others")
                {
                    lblInventor.Text = Strings.Inventor.ToString();
                    lblPatentNumber.Text = Strings.PatentNumber.ToString();
                    chkPCT.Visible = false;
                    chkFirstFiling.Visible = false;
                    Panel1.Visible = false;
                }
                else if (strname0 == "Patent")
                {
                    lblInventor.Text = Strings.Inventor.ToString();
                    lblPatentNumber.Text = Strings.PatentNumber.ToString();
                    chkPCT.Visible = true;
                    chkFirstFiling.Visible = true;
                    Panel1.Visible = true;
                }
            }
            else
            {
                lblInventor.Text = Strings.Designer.ToString();
                lblPatentNumber.Text = Strings.RegistrationNumber.ToString();
                chkPCT.Visible = false;
                chkFirstFiling.Visible = true;
                Panel1.Visible = true;
            }
        }
    }

    private void GetProjectDefault()
    {
        byte FilingEnabled;
        DateTime FirstFilingDate;
        DateTime PriorityDate;
        DateTime PCTPriorityDate;
        byte Expired;
        Project pj = new Project();
        string TargetProjectCode = "";
        string ProjectClass = "";
        string PCTCountry = "";
        int intRet = 0;
        Session["TargetProjectCode"] = "";
        Session["ProjectClass"] = "";
        Session["FirstFilingEnabled"] = "";
        Session["ProjectClass"] = "";
        Session["FirstFilingDate"] = "";
        Session["PriorityDate"] = "";
        Session["PCTCountry"] = "";
        Session["PCTPriorityDate"] = "";
        Session["PCTExpired"] = "";
        intRet = pj.CheckProjectFirstFiling(txtProjectGroupID.Text.ToString(), "", out TargetProjectCode, out FilingEnabled, out ProjectClass, out FirstFilingDate, out PriorityDate, out PCTCountry, out PCTPriorityDate, out Expired);
        Session["TargetProjectCode"] = TargetProjectCode.ToString();
        Session["ProjectClass"] = ProjectClass.ToString();
        Session["FirstFilingEnabled"] = FilingEnabled.ToString();
        Session["ProjectClass"] = ProjectClass.ToString();
        Session["FirstFilingDate"] = FirstFilingDate.ToString();
        Session["PriorityDate"] = PriorityDate.ToString();
        Session["PCTCountry"] = PCTCountry.ToString();
        Session["PCTPriorityDate"] = PCTPriorityDate.ToString();
        Session["PCTExpired"] = Expired.ToString();
        if (!string.IsNullOrEmpty(txtProjectGroupID.Text) && !chkForUpdate.Checked)
        {
            ProjectGroupClass runMethod = new ProjectGroupClass();
            runMethod.GetPGDefault(txtProjectGroupID.Text);
            try
            {
                txtClient.Text = runMethod.Client.ToString();
                PopulateClient();
                txtTitleSubject.Text = runMethod.TitleSubject.ToString();
                txtApplicant.Text = runMethod.Applicant.ToString();
                txtInventor.Text = runMethod.Inventor.ToString();
                txtProjectClass.Text = runMethod.ProjectClass.ToString();
                txtType.Text = runMethod.Type.ToString();
                lblError.Text = "";
                lblError.Visible = false;

            }
            catch (Exception)
            {
                txtProjectGroupID.Text = "";
                lblError.Text = Messages.ProjectGroupIDDoesNotExist.ToString();
                lblError.Visible = true;
            }
            if (runMethod.Type == "")
            {
                txtProjectGroupID.Text = "";
                lblError.Text = Messages.ProjectGroupIDDoesNotExist.ToString();
                lblError.Visible = true;
            }
        }
    }

    protected void GridToProjectInfo()
    {
        txtProjectGroupID.Text = base.Request.QueryString["pgi"].ToString();
        txtProjectCode.Text = GridView1.DataKeys[GridView1.SelectedIndex]["ProjectCode"].ToString();
        txtAgent.Text = GridView1.DataKeys[GridView1.SelectedIndex]["Agent"].ToString();
        txtTitleSubject.Text = GridView1.DataKeys[GridView1.SelectedIndex]["Title"].ToString();
        txtApplicant.Text = GridView1.DataKeys[GridView1.SelectedIndex]["Applicant"].ToString();
        txtInventor.Text = GridView1.DataKeys[GridView1.SelectedIndex]["Inventor"].ToString();
        txtApplicationNo.Text = GridView1.DataKeys[GridView1.SelectedIndex]["ApplicationNo"].ToString();
        txtPatentNumber.Text = GridView1.DataKeys[GridView1.SelectedIndex]["PatentNumber"].ToString();
        txtPriorityDate.Text = IPDataFormat.FormatDateTime(GridView1.DataKeys[GridView1.SelectedIndex]["PriorityDate"].ToString());
        txtClient.Text = GridView1.DataKeys[GridView1.SelectedIndex]["ClientName"].ToString();
        txtFilingDate.Text = IPDataFormat.FormatDateTime(GridView1.DataKeys[GridView1.SelectedIndex]["FilingDate"].ToString());
        txtGrantDate.Text = IPDataFormat.FormatDateTime(GridView1.DataKeys[GridView1.SelectedIndex]["GrantDate"].ToString());
        chkFirstFiling.Checked = Convert.ToBoolean(GridView1.DataKeys[GridView1.SelectedIndex]["FirstFilingYN"].ToString());
        if (chkFirstFiling.Checked)
        {
            txtFilingDate.CssClass = "required";
            RequiredFieldValidator5.Enabled = true;
        }
        else
        {
            txtFilingDate.CssClass = "";
            RequiredFieldValidator5.Enabled = false;
        }
        txtPublicationNumber.Text = GridView1.DataKeys[GridView1.SelectedIndex]["PublicationNumber"].ToString();
        txtRemarks.Text = GridView1.DataKeys[GridView1.SelectedIndex]["Remark"].ToString();
        txtAgentContactPerson3.Text = GridView1.DataKeys[GridView1.SelectedIndex]["AltContactPerson"].ToString();
        txtAgentContactFax3.Text = GridView1.DataKeys[GridView1.SelectedIndex]["AltContactFax"].ToString();
        txtAgentContactPhone3.Text = GridView1.DataKeys[GridView1.SelectedIndex]["AltContactPerson"].ToString();
        txtAgentContactEmail3.Text = GridView1.DataKeys[GridView1.SelectedIndex]["AltContactEmailAddress"].ToString();
        txtProjectClass.Text = GridView1.DataKeys[GridView1.SelectedIndex]["ProjectClass"].ToString();
        chkPriority.Checked = Convert.ToBoolean(GridView1.DataKeys[GridView1.SelectedIndex]["Priority"].ToString());
        Project runMethod2 = new Project();
        bool superUser = Convert.ToBoolean(Session["SuperUser"].ToString());
        runMethod2.GetProjectStatus(txtProjectCode.Text.ToString(), superUser, Session["OwnerGroupId"].ToString());
        if (runMethod2.Status == "Expired")
        {
            btnDelete.Enabled = false;
            btnModify.Enabled = false;
        }
        if (GridView1.DataKeys[GridView1.SelectedIndex]["Status"].ToString().ToLower() == "expired")
        {
            PrjInfoPanel.BackColor = ColorTranslator.FromHtml("#C0C0C0");
        }
        else
        {
            PrjInfoPanel.BackColor = ColorTranslator.FromHtml("#FFFFFF");
        }
    }

    protected void OnProjectClick(object sender, ImageClickEventArgs e)
    {
        if (sender == ibProjectInfo)
        {
            base.Response.Redirect("OptProjectInfo.aspx?pgi=" + txtProjectGroupID.Text.ToString() + "&type=" + txtType.Text.ToString() + "&pc=" + txtProjectCode.Text.ToString() + "&di=0&np=0");
        }
        else if (sender == ibViewDoc)
        {
            base.Response.Redirect("OptProjectDocument.aspx?pgi=" + txtProjectGroupID.Text.ToString() + "&type=" + txtType.Text.ToString() + "&pc=" + txtProjectCode.Text.ToString() + "&di=0&np=0");
        }
        else if (sender == ibProjectHeaderInfo)
        {
            base.Response.Redirect("OptProjectHeaderInfo.aspx?pgi=" + txtProjectGroupID.Text.ToString() + "&type=" + txtType.Text.ToString() + "&pc=" + txtProjectCode.Text.ToString() + "&di=0&np=0");
        }
        else if (sender == ibExpenditure)
        {
            base.Response.Redirect("OptProjectExpenses.aspx?pgi=" + txtProjectGroupID.Text.ToString() + "&type=" + txtType.Text.ToString() + "&pc=" + txtProjectCode.Text.ToString() + "&di=0&np=0");
        }
        else if (sender == ibGeneral)
        {
            string culture = ConvertToString(Session["Culture"]).ToLower();
            ibGeneral.ImageUrl = "~/Images/a_general_blue-" + culture + ".gif";
            ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
            ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
            ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
            PanelGeneral.Visible = true;
            PanelAgent.Visible = false;
            PanelClient.Visible = false;
            PanelOther.Visible = false;
        }
        else if (sender == ibAgent)
        {
            string culture = ConvertToString(Session["Culture"]).ToLower();
            ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
            ibAgent.ImageUrl = "~/Images/a_Agent_blue-" + culture + ".gif";
            ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
            ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
            PanelGeneral.Visible = false;
            PanelAgent.Visible = true;
            PanelClient.Visible = false;
            PanelOther.Visible = false;
        }
        else if (sender == ibClient)
        {
            string culture = ConvertToString(Session["Culture"]).ToLower();
            ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
            ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
            ibClient.ImageUrl = "~/Images/a_client_blue-" + culture + ".gif";
            ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
            PanelGeneral.Visible = false;
            PanelAgent.Visible = false;
            PanelClient.Visible = true;
            PanelOther.Visible = false;
        }
        else if (sender == ibOthers)
        {
            string culture = ConvertToString(Session["Culture"]).ToLower();
            ibGeneral.ImageUrl = "~/Images/a_General_gray-" + culture + ".gif";
            ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
            ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
            ibOthers.ImageUrl = "~/Images/a_others_blue-" + culture + ".gif";
            if (!txtProjectCode.Enabled | txtProjectCode.ReadOnly)
            {
                Session["ProjectCode"] = txtProjectCode.Text;
            }
            PanelGeneral.Visible = false;
            PanelAgent.Visible = false;
            PanelClient.Visible = false;
            PanelOther.Visible = true;
        }
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void LoadProjectInfo(string pgi, string pc, string type)
    {
        string culture = ConvertToString(Session["Culture"]).ToLower();
        ibGeneral.ImageUrl = "~/Images/a_General_blue-" + culture + ".gif";
        ibAgent.ImageUrl = "~/Images/a_Agent_gray-" + culture + ".gif";
        ibClient.ImageUrl = "~/Images/a_client_gray-" + culture + ".gif";
        ibOthers.ImageUrl = "~/Images/a_others_gray-" + culture + ".gif";
        PanelGeneral.Visible = true;
        btnModify.Visible = true;
        btnSave.Visible = true;
        btnDelete.Visible = true;
        btnCancel.Visible = true;

        bool isRestore = false;

        if (ViewState["isRestore"] != null)
        {
            if (Convert.ToBoolean(ViewState["isRestore"]))
            {
                isRestore = true;
            }
        }

        if (isRestore)
        {
            setButtons("restore");
        }
        else
        {
            setButtons(string.Empty);
        }

        PopulateProjectInfo(pgi, pc, type);
        EnableDisableByProjectType();
        PCTProcess(true);
        PrjInfoPanel.Visible = true;
        ProjectListPanel.Visible = false;
        ibExpenditure.Visible = true;
        ibProjectHeaderInfo.Visible = true;
        ibProjectInfo.Visible = true;
        ibViewDoc.Visible = true;
        txtProjectGroupID.Enabled = false;
        txtProjectCode.Focus();
        setTextReadOnly(true);
    }

    protected void OnProjectClassClick(object sender, EventArgs e)
    {
        if (sender == btnProjectClassOK)
        {
            if (gvChooseProjectClass.SelectedIndex >= 0)
            {
                txtProjectClass.Text = gvChooseProjectClass.DataKeys[gvChooseProjectClass.SelectedIndex].Values["ProjectClass"].ToString();
            }
        }
        else if (sender == btnProjectClassSetBlank)
        {
            txtProjectClass.Text = "";
        }
    }

    protected void PCTProcess(bool bPCTDisabled)
    {
        if ((projecttype == "Patent") | (txtType.Text == "Patent"))
        {
            if (!txtProjectCode.Enabled)
            {
                if (!chkPCT.Checked)
                {
                    chkPCT.Enabled = true;
                }
                if (Convert.ToBoolean(Session["SuperUser"].ToString()) & chkPCT.Checked)
                {
                    chkPCT.Enabled = true;
                }
                if ((!Convert.ToBoolean(Session["SuperUser"].ToString()) & chkPCT.Checked) && bPCTDisabled)
                {
                    chkPCT.Enabled = false;
                }
            }
            else
            {
                chkPCT.Enabled = true;
            }
            if (!chkPCT.Checked)
            {
                txtPriorityDate.Enabled = true;
            }
            else if (txtProjectCode.Enabled)
            {
                txtPriorityDate.Enabled = true;
            }
            else if (txtPriorityDate.Text != "")
            {
                txtPriorityDate.Enabled = false;
            }
            else
            {
                txtPriorityDate.Enabled = true;
            }
            if (chkPriority.Checked)
            {
                txtPriorityDate.Enabled = false;
            }
        }
    }

    protected void PopulateClient()
    {
        Client client = new Client(txtClient.Text.ToString());
        client.GetClientDetails();
        txtClientName.Text = client.Client_Name;
        txtClientChineseName.Text = client.Client_ChineseName;
        txtClientContactPerson.Text = client.Client_ContactPerson;
        txtClientAddress.Text = client.Client_Address;
        txtClientWebSite.Text = client.Client_WebSite;
        txtClientFax.Text = client.Client_Fax;
        txtClientPhone.Text = client.Client_Phone;
        txtClientPhone2.Text = client.Client_Phone2;
        txtClientContactPerson2.Text = client.Client_ContactPerson2;
        txtClientFax2.Text = client.Client_Fax2;
        txtClientEmailAddress.Text = client.Client_EmailAddress;
        txtClientEmailAddress2.Text = client.Client_EmailAddress2;
    }

    private void PopulateProjectInfo(string pgi, string projectCode, string type)
    {
        if ((GridView1.Rows.Count == 0) && ProjectListPanel.Visible)
        {
            ibGeneral.Visible = false;
            ibAgent.Visible = false;
            ibClient.Visible = false;
            ibOthers.Visible = false;
            btnModify.Visible = false;
            btnSave.Visible = false;
            btnDelete.Visible = false;
            btnCancel.Visible = false;
            PrjInfoPanel.Visible = false;
            ProjectListPanel.Visible = true;
            ibExpenditure.Visible = false;
            ibProjectHeaderInfo.Visible = false;
            ibProjectInfo.Visible = false;
            ibViewDoc.Visible = false;
            GridView1.DataBind();
            lblNoRecords.Visible = GridView1.Rows.Count == 0;
        }
        else
        {
            Project runMethod = new Project();
            if (string.IsNullOrEmpty(projectgroupid))
            {
                projectgroupid = pgi;
            }
            if (string.IsNullOrEmpty(projecttype))
            {
                projecttype = type;
            }
            if (string.IsNullOrEmpty(projecttype))
            {
                projecttype = GridView1.Rows[GridView1.SelectedIndex].Cells[2].Text.ToString();
            }
            runMethod.GetProjectInfo(projectgroupid, projectCode, projecttype);
            txtProjectGroupID.Text = projectgroupid;
            txtProjectCode.Text = projectCode;
            txtAgent.Text = runMethod.Agent;
            txtType.Text = projecttype;
            txtTitleSubject.Text = runMethod.Title;
            txtApplicant.Text = runMethod.Applicant;
            txtInventor.Text = runMethod.Inventor;
            txtApplicationNo.Text = runMethod.ApplicantNumber;
            txtPatentNumber.Text = runMethod.PatentNumber;
            txtPriorityDate.Text = IPDataFormat.FormatDateTime(runMethod.PriorityDate);
            txtClient.Text = runMethod.ClientName;
            txtFilingDate.Text = IPDataFormat.FormatDateTime(runMethod.FilingDate);
            txtGrantDate.Text = IPDataFormat.FormatDateTime(runMethod.GrantDate);
            chkFirstFiling.Checked = runMethod.FirstFilingYN;
            chkPCT.Checked = runMethod.PCTYN;
            if (chkFirstFiling.Checked)
            {
                txtFilingDate.CssClass = "required";
                RequiredFieldValidator5.Enabled = true;
            }
            else
            {
                txtFilingDate.CssClass = "";
                RequiredFieldValidator5.Enabled = false;
            }
            txtPublicationNumber.Text = runMethod.PublicationNumber;
            txtRemarks.Text = runMethod.Remarks;
            txtAgentContactPerson3.Text = runMethod.AgentContactPerson3;
            txtAgentContactFax3.Text = runMethod.AgentContactFax3;
            txtAgentContactPhone3.Text = runMethod.AgentContactPhone3;
            txtAgentContactEmail3.Text = runMethod.AgentContactEmail3;
            txtAgentContactPerson4.Text = runMethod.AgentContactPerson4;
            txtAgentContactFax4.Text = runMethod.AgentContactFax4;
            txtAgentContactPhone4.Text = runMethod.AgentContactPhone4;
            txtAgentContactEmail4.Text = runMethod.AgentContactEmail4;
            txtClientContactPerson3.Text = runMethod.ClientContactPerson3;
            txtClientContactFax3.Text = runMethod.ClientContactFax3;
            txtClientContactPhone3.Text = runMethod.ClientContactPhone3;
            txtClientContactEmail3.Text = runMethod.ClientContactEmail3;
            txtClientContactPerson4.Text = runMethod.ClientContactPerson4;
            txtClientContactFax4.Text = runMethod.ClientContactFax4;
            txtClientContactPhone4.Text = runMethod.ClientContactPhone4;
            txtClientContactEmail4.Text = runMethod.ClientContactEmail4;
            txtProjectClass.Text = runMethod.ProjectClass;
            chkPriority.Checked = runMethod.Priority;
            Project runMethod2 = new Project();
            bool superUser = Convert.ToBoolean(Session["SuperUser"].ToString());
            runMethod2.GetProjectStatus(txtProjectCode.Text.ToString(), superUser, Session["OwnerGroupId"].ToString());
            if (runMethod2.Status == "Expired")
            {
                btnDelete.Enabled = false;
                btnModify.Enabled = false;
            }
            if (runMethod.Status == "Expired")
            {
                PrjInfoPanel.BackColor = ColorTranslator.FromHtml("#C0C0C0");
            }
            else
            {
                PrjInfoPanel.BackColor = ColorTranslator.FromHtml("#FFFFFF");
            }
            if (txtAgent.Text != "")
            {
                Agent agent = new Agent(txtAgent.Text.ToString());
                agent.GetAgentDetails();
                txtAgentName.Text = agent.Agent_Name;
                txtAgentChineseName.Text = agent.Agent_ChineseName;
                txtAgentContactPerson.Text = agent.Agent_ContactPerson;
                txtAgentAddress.Text = agent.Agent_Address;
                txtAgentWebSite.Text = agent.Agent_WebSite;
                txtAgentFaxNo.Text = agent.Agent_Fax;
                txtAgentPhoneNo.Text = agent.Agent_Phone;
                txtAgentPhoneNo2.Text = agent.Agent_Phone2;
                txtAgentContactPerson2.Text = agent.Agent_ContactPerson2;
                txtAgentFaxNo2.Text = agent.Agent_Fax2;
                txtAgentEmailAddress.Text = agent.Agent_EmailAddress;
                txtAgentEmailAddress2.Text = agent.Agent_EmailAddress2;
            }
            if (txtClient.Text != "")
            {
                PopulateClient();
            }

            setTextReadOnly(false);

            ProjectDB objDB = new ProjectDB();
            grdProjectResponsiblePerson.DataSource = objDB.GetResponsiblePerson(projectCode);
            grdProjectResponsiblePerson.DataBind();

            grdProjectProduct.DataSource = objDB.GetProjectProduct(projectCode);
            grdProjectProduct.DataBind();
            objDB.CloseDB();
        }
    }

    public void setButtons(string action)
    {
        switch (action)
        {
            case "new":
                btnNew.Enabled = false;
                btnModify.Enabled = false;
                btnSave.Enabled = true;
                btnDelete.Enabled = false;
                btnRestore.Visible = false;
                EnableDisableByProjectType();
                return;

            case "modify":
                btnNew.Enabled = false;
                btnModify.Enabled = false;
                btnSave.Enabled = true;
                btnDelete.Enabled = false;
                btnRestore.Visible = false;
                return;
            case "restore":
                btnNew.Enabled = false;
                btnModify.Enabled = false;
                btnSave.Enabled = false;
                btnDelete.Visible = false;
                btnRestore.Visible = true;
                return;

        }

        btnModify.Enabled = SysUtil.IsAdministratorUsertype() || SysUtil.IsManagementSupervisor();

        if (!btnModify.Enabled)
        {
            ProjectDB objDB = new ProjectDB();

            btnModify.Enabled = objDB.IsResponsiblePersonOwner(txtProjectCode.Text.Trim(), Session[SysUtil.m_str_session_loginname].ToString());
            objDB.CloseDB();
        }

        btnNew.Enabled = btnModify.Enabled;
        btnSave.Enabled = false;
        btnDelete.Enabled = btnModify.Enabled;
        btnRestore.Visible = false;
    }

    protected void SetGrantDate()
    {
        if (txtPatentNumber.Text.Length != 0)
        {
            txtGrantDate.ReadOnly = false;
            txtGrantDate.BackColor = ColorTranslator.FromHtml("#FFFFC0");
            if (txtGrantDate.Text.Length == 0)
            {
                txtGrantDate.Text = IPDataFormat.ConvertDateFormat(DateTime.Now.ToShortDateString(), 2);
            }
        }
        else
        {
            txtGrantDate.Text = string.Empty;
        }
    }

    private void SetPCT(string strCountry)
    {
        if (strCountry.ToString() != "")
        {
            try
            {
                if (chkPCT.Enabled)
                {
                    chkPCT.Checked = new Country().GetPCT(strCountry.ToString());
                }
            }
            catch (Exception)
            {
                chkPCT.Checked = false;
            }
        }
    }

    private void setTextReadOnly(bool bBool)
    {
        txtProjectGroupID.ReadOnly = bBool;
        txtProjectCode.ReadOnly = bBool;
        btnPGI.Enabled = !bBool;

        if (chkForUpdate.Checked)
        {
        }

        ddlStatus.Enabled = !bBool;
        ddlCountry.Enabled = !bBool;
        btnAgent.Enabled = !bBool;
        txtTitleSubject.ReadOnly = bBool;
        txtApplicant.ReadOnly = bBool;
        txtInventor.ReadOnly = bBool;
        txtApplicationNo.ReadOnly = bBool;
        txtPatentNumber.ReadOnly = bBool;
        txtPriorityDate.Enabled = false;
        ddlPriorityCountry.Enabled = false;
        btnClient.Enabled = !bBool;
        txtAgentContactPerson3.Enabled = !bBool;
        txtAgentContactFax3.Enabled = !bBool;
        txtAgentContactPhone3.Enabled = !bBool;
        txtAgentContactEmail3.Enabled = !bBool;
        txtAgentContactPerson4.Enabled = !bBool;
        txtAgentContactFax4.Enabled = !bBool;
        txtAgentContactPhone4.Enabled = !bBool;
        txtAgentContactEmail4.Enabled = !bBool;
        txtFilingDate.Enabled = !bBool;
        txtGrantDate.Enabled = !bBool;
        txtPublicationNumber.ReadOnly = bBool;
        txtRemarks.ReadOnly = bBool;
        txtProjectClass.ReadOnly = bBool;
        btnProjectClass.Enabled = !bBool;
        chkFirstFiling.Enabled = !bBool;
        chkPriority.Enabled = !bBool;
        chkPCT.Enabled = !bBool;
    }

    protected void showRow()
    {
        string showRow_javaScript = "<script type='text/javascript' language='javascript'> \n";
        showRow_javaScript = ((showRow_javaScript + "if (" + base.Request.QueryString["np"].ToString() + "==1) { \n") + "   document.getElementById('PGID').style.display = 'inline'; } \n" + " else { \n") + "   document.getElementById('PGID').style.display = 'none';  \n" + "} </script>";
        base.ClientScript.RegisterStartupScript(Page.GetType(), "regShowRow", showRow_javaScript);
    }

    protected void Sort(GridViewRowEventArgs e, GridView gv)
    {
        if ((e.Row != null) && (e.Row.RowType == DataControlRowType.Header))
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = (LinkButton) cell.Controls[0];
                    if (button != null)
                    {
                        System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
                        image.ImageUrl = "";
                        if (gv.SortExpression == button.CommandArgument)
                        {
                            if (gv.SortDirection == SortDirection.Ascending)
                            {
                                image.ImageUrl = "images/sortup.gif";
                            }
                            else
                            {
                                image.ImageUrl = "images/sortdown.gif";
                            }
                        }
                        if (image.ImageUrl != "")
                        {
                            cell.Controls.Add(image);
                        }
                    }
                }
            }
        }
    }

    protected void OnTextChanged(object sender, EventArgs e)
    {
        if (sender == txtGrantDate)
        {
            if (txtGrantDate.Text.Length != 0)
            {
                ddlStatus.SelectedIndex = -1;
                ddlStatus.Items.FindByText("In Force").Selected = true;
            }
            else if (txtPatentNumber.Text.Length == 0)
            {
                ddlStatus.SelectedIndex = -1;
            }
        }
        else if (sender == txtPatentNumber)
        {
            SetGrantDate();
            if (txtPatentNumber.Text.Length != 0)
            {
                ddlStatus.SelectedIndex = -1;
                ddlStatus.Items.FindByText("In Force").Selected = true;
            }
        }
        else if (sender == txtProjectGroupID)
        {
            if (txtProjectGroupID.Text != "")
            {
                GetProjectDefault();
                EnabledDisabledPriority("New");
            }
        }
    }

    private string ConvertToString(object obj, string strDefault)
    {
        if (obj != null)
        {
            return obj.ToString();
        }

        return strDefault;
    }

    private string ConvertToString(object obj)
    {
        return ConvertToString(obj, "");
    }
}
